import BaseService from "./BaseService";
export default class WebSocketService extends BaseService {

    protected socket: WebSocket;


    destroy() {
        if (this.socket != null) {
            this.socket.close();
            this.socket = null;
        }
    }
    //手动重联
    reConnect() {
        this.connect();
    }

    onData(event) {
        super.onData(event.data);
    }

    connect() {
        this.destroy();
        try {
            let self = this
            this.socket = new WebSocket(this.url);
            this.socket.binaryType = "arraybuffer";
            this.socket.onopen = function (event) {
                self.onOpen(event);
            };
            this.socket.onmessage = function (event) {
                self.onData(event);
            };
            this.socket.onerror = function (event) {
                self.onError(event);
            };
            this.socket.onclose = function (event) {
                self.onClose(event);
            };
        } catch (error) {
            console.log("WebService connect error " + error);
        }
    }

    sendData(message: net.SendMessage) {
        if (this.isReady() && this.socket) {
            this.socket.send(message.data);
        } else {
            console.warn(" 请先连接服务器 ", this.url);
        }
    }



}
